//
//  CommunityTopicTableCell.m
//  ArtDog
//
//  Created by dllo on 16/9/3.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CommunityTopicTableCell.h"
#import "BaseCollectionView.h"
#import "CommunityTopicList.h"
#import "UIImageView+WebCache.h"
#import "NSString+Common.h"
#import "ImageViewCollectionCell.h"
#import "HLMacro.h"
#import "ZWYNetTool.h"
#import "MineMainViewController.h"
#import "UIView+Common.h"

#import "CommunityTopicLabelList.h"
#import "CommunityHotCommentList.h"
#import "CommunityPicture.h"
#import "TopCollectionLayout.h"
#import "LabelCollectionViewCell.h"
#import "CommunityMainCellContentController.h"
#import "ImageCollectViewController.h"
#import "UIColor+Common.h"

static CommunityTopicTableCell *cellIsUnfold;
static CommunityTopicTableCell *currentCell;
static CGFloat cellHeight;
static NSIndexPath *sIndexPath;

@interface CommunityTopicTableCell ()<UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource, TopCollectionLayoutDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageCollectionHeight;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionTopLayout;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *praiseTopLayout;

@property (weak, nonatomic) IBOutlet UIImageView *headPicImage;
@property (weak, nonatomic) IBOutlet UILabel *username;
@property (weak, nonatomic) IBOutlet UIButton *workerBtn;
@property (weak, nonatomic) IBOutlet UILabel *topicDescLabel;
@property (weak, nonatomic) IBOutlet UIButton *isUnfoldBtn;
@property (weak, nonatomic) IBOutlet UIImageView *isUnfoldImage;

@property (weak, nonatomic) IBOutlet UILabel *praiseNumLabel;

@property (nonatomic, assign) BOOL isChangeConfig;


@end

@implementation CommunityTopicTableCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [_workerBtn addTarget:self action:@selector(workerAction:) forControlEvents:UIControlEventTouchUpInside];
    [_isUnfoldBtn addTarget:self action:@selector(isUnfoldAction:) forControlEvents:UIControlEventTouchUpInside];
    [_seeAllBtn addTarget:self action:@selector(seeAllAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    //[_isUnfoldBtn setTitle:@"展开" forState:UIControlStateNormal];
    _isOpen = NO;
    _topicDescLabel.numberOfLines = 4;
}

#pragma mark - set model
- (void)setTopicModel:(CommunityTopicList *)topicModel
{
    _topicModel = topicModel;
    currentCell = self;
    if (cellIsUnfold != nil && sIndexPath != nil && [cellIsUnfold.isUnfoldBtn.titleLabel.text isEqualToString:@"展开"] && [topicModel.idField intValue] == [cellIsUnfold.topicModel.idField intValue]) {
        _isOpen = YES;
        cellIsUnfold = nil;
        UIButton *button = [self viewWithTag:200];
        button.tag = 199;
        
    } else if (cellIsUnfold != nil && sIndexPath != nil && [topicModel.idField intValue] == [cellIsUnfold.topicModel.idField intValue]) {
        UIButton *button = [self viewWithTag:200];
        button.tag = 199;
    }
    _isChangeConfig = NO;
    cellHeight = SCREEN_WIDTH - 30 + 440;
    [_headPicImage sd_setImageWithURL:[NSURL URLWithString:topicModel.headPic] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    _username.text = topicModel.userName;
    
    [self setupBtnModel:topicModel];
    [self setupCollectionViewWithModel:topicModel];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    [style setLineSpacing:3.0f];
    _topicDescLabel.attributedText = [[NSAttributedString alloc]initWithString:topicModel.topicDesc attributes:@{NSParagraphStyleAttributeName: style}];
    _praiseNumLabel.text = [NSString stringWithFormat:@"%@", topicModel.praiseNum];
    _commentLabel.text = [NSString stringWithFormat:@"%@", topicModel.joinNum];
    
    _commentContentOne.hidden = YES;
    _commentUsernameOne.hidden = YES;
    _commentContentTwo.hidden = YES;
    _commentUsernmameTwo.hidden = YES;
    _commentContentThree.hidden = YES;
    _commentUsernameThree.hidden = YES;
    _seeAllBtn.hidden = YES;
    _nextImage.hidden = YES;
    cellHeight = cellHeight - 130;
    if (topicModel.hotCommentList.count != 0) {
        for (int i = 0; i < topicModel.hotCommentList.count; i++) {
            if (i == 0) {
                _commentUsernameOne.text = [topicModel.hotCommentList[0].userName stringByAppendingString:@"："];
                _commentContentOne.text = topicModel.hotCommentList[0].commentTxt;
                _commentContentOne.hidden = NO;
                _commentUsernameOne.hidden = NO;
                cellHeight = cellHeight + 45;
            } else if (i == 1) {
                _commentUsernmameTwo.text = [topicModel.hotCommentList[1].userName stringByAppendingString:@"："];
                _commentContentTwo.text = topicModel.hotCommentList[1].commentTxt;
                _commentContentTwo.hidden = NO;
                _commentUsernmameTwo.hidden = NO;
                cellHeight = cellHeight + 25;
            } else if (i == 2) {
                _commentUsernameThree.text = [topicModel.hotCommentList[2].userName stringByAppendingString:@"："];
                _commentContentThree.text = topicModel.hotCommentList[2].commentTxt;
                _commentContentThree.hidden = NO;
                _commentUsernameThree.hidden = NO;
                _seeAllBtn.hidden = NO;
                _nextImage.hidden = NO;
                cellHeight = cellHeight + 60;
                
            } 
        }
    }
    
    
}

- (void)setupCollectionViewWithModel:(CommunityTopicList *)topicModel
{
    if (topicModel.pictures.count == 0) {
        _imageCollectionView.hidden = YES;
        _imageCollectionHeight.constant = - SCREEN_WIDTH;
        cellHeight = cellHeight - SCREEN_WIDTH + 30;
    } else if (topicModel.pictures.count == 2){
        _imageCollectionView.hidden = NO;
        CGFloat multip = 0.5;
        _imageCollectionHeight.constant = - (SCREEN_WIDTH - 30) * multip - 30;
        cellHeight = cellHeight - (SCREEN_WIDTH - 30) / 2;
    } else if (topicModel.pictures.count > 4 && topicModel.pictures.count <= 6) {
        _imageCollectionView.hidden = NO;
        CGFloat multip = 0.333334;
        _imageCollectionHeight.constant = - (SCREEN_WIDTH - 30) * multip - 30;
        cellHeight = cellHeight - (SCREEN_WIDTH - 30) / 3;
    } else {
        _imageCollectionView.hidden = NO;
        CGFloat multip = 0;
        _imageCollectionHeight.constant = - (SCREEN_WIDTH - 30) * multip - 30;
    }
    _imageCollectionView.backgroundColor = [UIColor whiteColor];
    _imageCollectionView.scrollEnabled = NO;
    _imageCollectionView.delegate = self;
    _imageCollectionView.dataSource = self;
    [_imageCollectionView registerNib:[UINib nibWithNibName:@"ImageViewCollectionCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"imageViewCollectionCell"];
    [_imageCollectionView reloadData];
    
    if (topicModel.topicLabelList.count == 0) {
        _labelCollectionView.hidden = YES;
        _praiseTopLayout.constant = 20;
        cellHeight = cellHeight - 25;
    } else {
        _labelCollectionView.hidden = NO;
        _praiseTopLayout.constant = 45;
    }
    _labelCollectionView.backgroundColor = [UIColor whiteColor];
    _labelCollectionView.scrollEnabled = NO;
    TopCollectionLayout *layout = (TopCollectionLayout *)_labelCollectionView.collectionViewLayout;
    layout.delegate = self;
    layout.minimumIteritemSpacing = 10;
    [_labelCollectionView registerNib:[UINib nibWithNibName:@"LabelCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"labelCollectionViewCell"];
    [_labelCollectionView reloadData];
    [_labelCollectionView collectionViewWithNumberOfItems:^(UICollectionView * _Nonnull collectionView, CollectionViewReturnParam * _Nonnull collectionViewParam) {
        collectionViewParam.numberOfItems = topicModel.topicLabelList.count;
    } andCellForItemAtIndexPath:^(UICollectionView * _Nonnull collectionView, NSIndexPath * _Nonnull indexPath, CollectionViewReturnParam * _Nonnull collectionViewParam) {
        LabelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"labelCollectionViewCell" forIndexPath:indexPath];
        cell.labelModel = topicModel.topicLabelList[indexPath.item];
        collectionViewParam.returnCell = cell;
    }];
}

- (void)setupBtnModel:(CommunityTopicList *)topicModel
{
    // workerBtn
    if ([topicModel.isWatch integerValue] == 0) {
        [_workerBtn setTitle:@"关注" forState:UIControlStateNormal];
        [_workerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _workerBtn.backgroundColor = [UIColor whiteColor];
    } else {
        [_workerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_workerBtn setTitle:@"已关注" forState:UIControlStateNormal];
        [_workerBtn setBackgroundColor:[UIColor blackColor]];
    }
    
    
    // isUnfoldBtn
    CGFloat topicDescHeight = [topicModel.topicDesc calculateWordsHeightWithFontSize:14 andWidth:self.contentView.frame.size.width - 30];
    if (topicDescHeight > 80) {
        _isUnfoldBtn.hidden = NO;
        _isUnfoldImage.hidden = NO;
        _collectionTopLayout.constant = 54;
        if (_isOpen) {
            [_isUnfoldBtn setTitle:@"收起" forState:UIControlStateNormal];
            _isUnfoldImage.image = [UIImage imageNamed:@"pack"];
            _topicDescLabel.numberOfLines = 0;
            cellHeight = cellHeight - 80 + [_topicModel.topicDesc calculateWordsHeightWithFontSize:14 andWidth:SCREEN_WIDTH - 30] * 1.2;
            
        } else {
            [_isUnfoldBtn setTitle:@"展开" forState:UIControlStateNormal];
            _isUnfoldImage.image = [UIImage imageNamed:@"unfold"];
            _topicDescLabel.numberOfLines = 4;
        }
    } else {
        _isUnfoldBtn.hidden = YES;
        _isUnfoldImage.hidden = YES;
        _collectionTopLayout.constant = 25;
        cellHeight = cellHeight - 19 - 80 + topicDescHeight;
    }
    
}

#pragma mark - button 点击方法
- (void)workerAction:(UIButton *)button
{
    CommunityTopicTableCell *cell = (CommunityTopicTableCell *)button.superview.superview;
    NSString *tokenString = [@"token=" stringByAppendingString:[[[NSString getUserDefaultToken] stringByAppendingString:@"&watchUserId="] stringByAppendingString:[NSString stringWithFormat:@"%@", cell.topicModel.userId]]];
    if ([button.titleLabel.text isEqualToString:@"关注"]) {
        if (![[NSString getUserDefaultId] isEqualToString:@"0"]) {
            NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"watchSecond"] andParams:tokenString];
            [ZWYNetTool POST:urlString andBody:[@"Content-Length: 61\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: api.artgoer.cn:8084\r\nConnection: Keep-Alive\r\nAccept-Encoding: gzip\r\n\r\n" stringByAppendingString:tokenString] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Length": @"61", @"Content-Type": @"application/x-www-form-urlencoded", @"Host": @"api.artgoer.cn:8084", @"Connection": @"Keep-Alive", @"Accept-Encoding": @"gzip"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
                
                if ([result[@"status"] isEqualToString:@"200"]) {
                    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [button setTitle:@"已关注" forState:UIControlStateNormal];
                    [button setBackgroundColor:[UIColor blackColor]];
                    _topicModel.isWatch = @1;
                }
            } andFailureBlock:^(NSError *error) {
                NSLog(@"%@", error);
            }];
        } else {
            UIViewController *vc = [self getVCRecently];
            vc.tabBarController.selectedIndex = 3;
            UINavigationController *mineNavi = vc.tabBarController.viewControllers[3];
            MineMainViewController *mineVC = mineNavi.viewControllers[0];
            mineVC.lastIndex = 1;
        }
    } else {
        if (![[NSString getUserDefaultId] isEqualToString:@"0"]) {
            NSString *urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"unWatch"] andParams:tokenString];
            [ZWYNetTool POST:urlString andBody:[@"Content-Length: 61\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: api.artgoer.cn:8084\r\nConnection: Keep-Alive\r\nAccept-Encoding: gzip\r\n\r\n" stringByAppendingString:tokenString] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/x-www-form-urlencoded", @"Host": @"api.artgoer.cn:8084"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
                if ([result[@"status"] isEqualToString:@"200"]) {
                    [button setTitle:@"关注" forState:UIControlStateNormal];
                    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    [button setBackgroundColor:[UIColor whiteColor]];
                    _topicModel.isWatch = @0;
                }
            } andFailureBlock:^(NSError *error) {
                NSLog(@"%@", error);
            }];
        } else {
            UIViewController *vc = [self getVCRecently];
            vc.tabBarController.selectedIndex = 3;
            UINavigationController *mineNavi = vc.tabBarController.viewControllers[3];
            MineMainViewController *mineVC = mineNavi.viewControllers[0];
            mineVC.lastIndex = 1;
        }
    }
}

- (void)isUnfoldAction:(UIButton *)button
{
    if (button.tag == 200) {
        button.tag = 199;
        return;
    }
    button.tag = 200;
    UITableView *tableView = (UITableView *)self.superview.superview;
    CommunityTopicTableCell *cell = (CommunityTopicTableCell *)button.superview.superview;
    cellIsUnfold = cell;
    sIndexPath = [tableView indexPathForCell:cell];
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:@[sIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    [tableView endUpdates];
    tableView.contentOffset = CGPointMake(0, [cell convertRect:cell.bounds toView:tableView].origin.y);
}

- (void)seeAllAction:(UIButton *)button
{
    CommunityMainCellContentController *cellContentVC = [[CommunityMainCellContentController alloc]init];
    cellContentVC.topicModel = _topicModel;
    cellContentVC.isOffset = YES;
    UIViewController *vc = [self getVCRecently];
    [vc.navigationController pushViewController:cellContentVC animated:YES];
}

#pragma mark - collectionView 代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_topicModel.pictures.count <= 9) {
        return _topicModel.pictures.count;
    } else {
        return 9;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageViewCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageViewCollectionCell" forIndexPath:indexPath];
    cell.pictureModel = _topicModel.pictures[indexPath.item];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isChangeConfig == YES) {
        return CGSizeMake(SCREEN_WIDTH - 30, SCREEN_WIDTH - 30);
    }
    if (_topicModel.pictures.count == 0) {
        return CGSizeZero;
    } else if (_topicModel.pictures.count == 1) {
        return CGSizeMake(SCREEN_WIDTH - 30, SCREEN_WIDTH - 30);
    } else if (_topicModel.pictures.count <= 4) {
        return CGSizeMake((SCREEN_WIDTH - 38) / 2, (SCREEN_WIDTH - 38) / 2);
    } else {
        return CGSizeMake((SCREEN_WIDTH - 46) / 3, (SCREEN_WIDTH - 46) / 3);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageCollectViewController *imageVC = [[ImageCollectViewController alloc]init];
    imageVC.pictures = _topicModel.pictures;
    imageVC.indexPath = indexPath;
    
    UIViewController *vc = [self getVCRecently];
    [vc.navigationController pushViewController:imageVC animated:YES];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 8;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

#pragma mark - topLayout delegate
- (CGSize)collectionView:(UICollectionView *)collectionView topLayout:(TopCollectionLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *labelName = _topicModel.topicLabelList[indexPath.item].labelName;
    
    
    NSAttributedString *string = [[NSAttributedString alloc]initWithString:labelName attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13]}];
    
    CGRect newRect = [string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 20) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    return CGSizeMake(newRect.size.width + 20, 20);
}

#pragma mark - cell 高度
+ (CGFloat)getCellHeight
{
    return cellHeight;
}

- (void)changeCellConfig
{
    [self hideCommentContent];
    [self setupImageCollectionView];
}


- (void)hideCommentContent
{
    if (self.topicModel.hotCommentList.count != 0) {
        for (int i = 0; i < self.topicModel.hotCommentList.count; i++) {
            if (i == 0) {
                self.commentContentOne.hidden = YES;
                self.commentUsernameOne.hidden = YES;
                cellHeight = cellHeight - 45;
            } else if (i == 1) {
                self.commentContentTwo.hidden = YES;
                self.commentUsernmameTwo.hidden = YES;
                cellHeight = cellHeight - 25;
            } else if (i == 2) {
                self.commentContentThree.hidden = YES;
                self.commentUsernameThree.hidden = YES;
                self.seeAllBtn.hidden = YES;
                self.nextImage.hidden = YES;
                cellHeight = cellHeight - 60;
            }
        }
    }
    
}

- (void)setupImageCollectionView
{
    _imageCollectionHeight.constant = -SCREEN_WIDTH + _topicModel.pictures.count * (SCREEN_WIDTH - 30);
    cellHeight = cellHeight + _imageCollectionHeight.constant + 30;
    //_imageCollectionView.scrollEnabled = YES;
    _isChangeConfig = YES;
    _imageCollectionView.showsVerticalScrollIndicator = NO;
    if (_isUnfoldBtn.hidden == NO && [_isUnfoldBtn.titleLabel.text isEqualToString:@"展开"]) {
        _topicDescLabel.numberOfLines = 0;
        _isUnfoldBtn.hidden = YES;
        _isUnfoldImage.hidden = YES;
        cellHeight = cellHeight - 80 + [_topicModel.topicDesc calculateWordsHeightWithFontSize:14 andWidth:SCREEN_WIDTH - 30] * 1.2;
    }
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

}

@end
